package com.r_z.service.impl;

import com.r_z.entity.Storages;
import com.r_z.entity.StoragesDetails;
import com.r_z.mapper.StoragesMapper;
import com.r_z.service.StoragesImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StoragesImplService implements StoragesImpl {
    @Autowired
    private StoragesMapper storagesMapper;

    @Override
    public List<Storages> selectStorages(int page, int limit, String nowTime, int storageinState) {
        String where = appendWhere(nowTime, storageinState);
        int pages = (page - 1) * limit;
        List<Storages> storagesList = storagesMapper.selectStorages(pages, limit, where);
        for (Storages storages : storagesList) {
            StoragesDetails storagesDetails = storagesMapper.selectDetail(storages.getPurchaseId());
            storages.setStoragesDetails(storagesDetails);
        }
        return storagesList;
    }

    @Override
    public StoragesDetails selectDetail(String purchaseId) {
        return storagesMapper.selectDetail(purchaseId);
    }


    @Override
    public int getTotal(String where, int storageinState) {
        return storagesMapper.getTotal(appendWhere(where, storageinState));
    }

    @Override
    public int approve(String purchaseId, int goodId, int num) {
        addFlag(goodId, num);
        return storagesMapper.approve(purchaseId);
    }

    public void addFlag(int goodId, int num) {
        int count = storagesMapper.repertoryCount(goodId);
        if (count >= 1) {
            storagesMapper.repertoryInsert(num, goodId);
        } else {
            storagesMapper.repertoryAdd(num, goodId);
        }
    }

    private String appendWhere(String nowTime, int storageinState) {
        StringBuilder sb = new StringBuilder();
        if (nowTime != null && !nowTime.equals("")) {
            sb.append(" and p.nowTime='").append(nowTime).append("'");
        }
        if (storageinState != 3) {
            sb.append(" and p.storageinState='").append(storageinState).append("'");
        }
        return sb.toString();
    }

}
